package com.demo.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class InitView extends JFrame {

	private static final long serialVersionUID = -6508797200616193580L;

	private JButton mDoneButton;
	private JTextField mPath;

	private InitView(String defaultPath) {
		super("Low Java Editor");
		this.setSize(320, 76);
		this.setLayout(new BorderLayout(5, 5));

		Container container = getContentPane();

		JLabel message = new JLabel("Select default workspace location");
		container.add(message, BorderLayout.NORTH);

		mPath = new JTextField(defaultPath);
		mPath.setPreferredSize(new Dimension(196, 48));
		container.add(mPath, BorderLayout.WEST);

		JButton select = new JButton("...");
		select.setPreferredSize(new Dimension(36, 36));
		select.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				selectSearchPath();
			}
		});
		container.add(select, BorderLayout.CENTER);

		mDoneButton = new JButton("Done");
		container.add(mDoneButton, BorderLayout.EAST);

		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	private void selectSearchPath() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		if (!getPath().isEmpty()) {
			chooser.setCurrentDirectory(new File(getPath()));
		}
		chooser.showOpenDialog(this);
		File file = chooser.getSelectedFile();
		if (file != null) {
			mPath.setText(file.getAbsolutePath());
		}
	}

	public void showError() {
		JOptionPane.showMessageDialog(null, "path can not be null", "Error", JOptionPane.ERROR_MESSAGE);
	}

	public String getPath() {
		return mPath.getText();
	}

	public static InitView newInstance(String defaultPath) {
		return new InitView(defaultPath);
	}

	public JButton getDoneButton() {
		return mDoneButton;
	}

	public void close() {
		this.setVisible(false);
	}

}
